//
//  ComposeViewController.swift
//  XNWeiBo_Swift
//
//  Created by xunan on 2017/1/11.
//  Copyright © 2017年 xunan. All rights reserved.
//

import UIKit
import SVProgressHUD

enum XNComposeToolbarButtonType {
    case HWComposeToolbarButtonTypePicture
    case HWComposeToolbarButtonTypeMention
    case HWComposeToolbarButtonTypeTrend
    case HWComposeToolbarButtonTypeEmotion
    case HWComposeToolbarButtonTypeCamera
}

class ComposeViewController: UIViewController {
    
    // 表情键盘
    private lazy var emotionVC: EmoticonViewController = EmoticonViewController {
        [unowned self] (emoticon) -> () in
        self.textView.insertEmoticon(emoticon)
    }
    // 图片选择器
    private lazy var photoSelectorVC: PhotoSelectorViewController = PhotoSelectorViewController()
    

    /// 工具条底部约束
    var toolbarBottomCons: NSLayoutConstraint?
    // 图片选择器高度约束
    var photoViewHeightCons: NSLayoutConstraint?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        // 0.注册通知监听键盘的弹出和消失
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ComposeViewController.keyboardChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        // 1.将键盘控制器添加为当前控制器的子控制器
        addChildViewController(emotionVC)
        addChildViewController(photoSelectorVC)
        
        // 1.初始化导航栏
        setupNav()
        
        // 2.输入框
        setupInputView()
        
        // 3.初始化图片选择器
        setupPhotoView()
        
        // 3.初始化工具条
        setupToolbar()
        
    }
    
    func keyboardChange(notify: NSNotification)
    {
        // 1.取出键盘最终的rect
        let value = notify.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue
        let rect = value.CGRectValue()
        
        // 2.修改工具条的约束
        let height = UIScreen.mainScreen().bounds.height
        toolbarBottomCons?.constant = -(height - rect.origin.y)
        
        // 3.更新界面
        let duration = notify.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
        
        // 1.取出键盘的动画节奏
        let curve = notify.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
        
        UIView.animateWithDuration(duration.doubleValue) {
            
            // 2.设置动画节奏
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve.integerValue)!)
            
            self.view.layoutIfNeeded()
        }
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        if photoViewHeightCons?.constant == 0
        {
            // 主动召唤键盘
            textView.becomeFirstResponder()
        }
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        textView.resignFirstResponder()
    }
    
    private func setupToolbar() {
        // 1.添加子控件
        view.addSubview(toolbar)
        view.addSubview(tipLabel)
        
        let titleArr = ["compose_toolbar_picture", "compose_mentionbutton_background", "compose_trendbutton_background", "compose_emoticonbutton_background", "compose_camerabutton_background"]
        let btnWidth = UIScreen.mainScreen().bounds.width / CGFloat(titleArr.count)
        
        for index in 0...4 {
            let btn = UIButton()
            btn.frame = CGRectMake(CGFloat(index) * btnWidth, 0, btnWidth, 49)
            btn.tag = index + 100
            btn.setImage(UIImage(named: titleArr[index]), forState: UIControlState.Normal)
            btn.addTarget(self, action: #selector(ComposeViewController.tagBtnWithIndex(_:)), forControlEvents: UIControlEvents.TouchUpInside)
            toolbar.addSubview(btn)
        }
        
        // 3.布局toolBar
        let width = UIScreen.mainScreen().bounds.width
        let cons = toolbar.xmg_AlignInner(type: XMG_AlignType.BottomLeft, referView: view, size: CGSizeMake(width, 44))
        toolbarBottomCons = toolbar.xmg_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
   
        tipLabel.xmg_AlignVertical(type: XMG_AlignType.TopRight, referView: toolbar, size: nil, offset: CGPointMake(-10, -10))
    }
    
    func setupPhotoView() {
        
        // 1.添加图片选择器
        view.insertSubview(photoSelectorVC.view, belowSubview: toolbar)
        
        // 2.布局图片选择器
        let size = UIScreen.mainScreen().bounds.size
        let width = size.width
        let height: CGFloat = 0
        let cons = photoSelectorVC.view.xmg_AlignInner(type: XMG_AlignType.BottomLeft, referView: view, size: CGSizeMake(width, height))
        photoViewHeightCons = photoSelectorVC.view.xmg_Constraint(cons, attribute: NSLayoutAttribute.Height)
    }
    
    @objc private func tagBtnWithIndex(btn: UIButton) {
        switch btn.tag {
        case 100:
            // 1.关闭键盘
            textView.resignFirstResponder()
            
            // 2.调整图片选择器的高度
            photoViewHeightCons?.constant = UIScreen.mainScreen().bounds.height * 0.6
            break
        case 101:
            break
        case 102:
            break
        case 103:
            // 1.关闭键盘
            textView.resignFirstResponder()
            
            // 2.设置inputView
            textView.inputView = (textView.inputView == nil) ? emotionVC.view : nil
            
            // 3.从新召唤出键盘
            textView.becomeFirstResponder()
            break
        case 104:
            break
        default:
            break
        }
    }
    
    private func setupInputView() {
        // 1.添加子控件
        view.addSubview(textView)
        textView.addSubview(placeholderLabel)
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        // 2.布局子控件
        textView.xmg_Fill(view)
        placeholderLabel.xmg_AlignInner(type: XMG_AlignType.TopLeft, referView: textView, size: nil, offset: CGPoint(x: 5, y: 8))
    }
    
    private func hh() {
        
    }
    
    private func setupNav() {
        // 1.添加左边按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ComposeViewController.close))
        
        // 2.添加右边按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ComposeViewController.sendStatus))
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 3.添加中间视图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 32))
        let label1 = UILabel()
        label1.text = "发送微博"
        label1.font = UIFont.systemFontOfSize(15)
        label1.sizeToFit()
        titleView.addSubview(label1)
        
        let label2 = UILabel()
        label2.text = UserAccount.loadAccount()?.screen_name
        label2.font = UIFont.systemFontOfSize(13)
        label2.textColor = UIColor.darkGrayColor()
        label2.sizeToFit()
        titleView.addSubview(label2)
        
        label1.xmg_AlignInner(type: XMG_AlignType.TopCenter, referView: titleView, size: nil)
        label2.xmg_AlignInner(type: XMG_AlignType.BottomCenter, referView: titleView, size: nil)
        
        navigationItem.titleView = titleView

    }
    
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /**
     发送文本微博
     */
    func sendStatus() {
        
        let text = textView.emoticonAttributedText()
        let image = photoSelectorVC.pictureImages.first
        NetworkTools.shareNetworkTools().sendStatus(text , image: image, successCallback: { (status) -> () in
            // 1.提示用户发送成功
            SVProgressHUD.showSuccessWithStatus("发送成功", maskType: SVProgressHUDMaskType.Black)
            // 2.关闭发送界面
            self.close()
        }) { (error) -> () in
            print(error)
            // 3.提示用户发送失败
            SVProgressHUD.showErrorWithStatus("发送失败", maskType: SVProgressHUDMaskType.Black)
        }

    }
    
    // MARK: - 懒加载
    private lazy var textView: UITextView = {
        let tv = UITextView()
        tv.delegate = self
        return tv
    }()
    
    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(13)
        label.textColor = UIColor.darkGrayColor()
        label.text = "分享新鲜事..."
        return label
    }()
    
    private lazy var toolbar: UIToolbar = UIToolbar()
    
    private lazy var tipLabel: UILabel = {
        let label = UILabel()
        return label
    }()
}
private let maxTipLength = 10
extension ComposeViewController: UITextViewDelegate
{
    func textViewDidChange(textView: UITextView) {
        placeholderLabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    
        // 当前已经输入的内容长度
        let count = textView.emoticonAttributedText().characters.count
        let res = maxTipLength - count
        tipLabel.textColor = (res > 0) ? UIColor.darkGrayColor() : UIColor.redColor()
        tipLabel.text = res == maxTipLength ? "" : "\(res)"
    }
}



